using MediatR;
using STD.Shared.Common.Helpers;
using STD.Services.UserService.Domain.Entities;
using STD.Services.UserService.Domain.Repositories;

namespace STD.Services.UserService.Application.Commands;

/// <summary>
/// 创建用户命令
/// </summary>
public class CreateUserCommand : IRequest<Result<User>>
{
    /// <summary>
    /// 用户名
    /// </summary>
    public string Username { get; set; } = string.Empty;
    
    /// <summary>
    /// 邮箱
    /// </summary>
    public string Email { get; set; } = string.Empty;
    
    /// <summary>
    /// 密码
    /// </summary>
    public string Password { get; set; } = string.Empty;
    
    /// <summary>
    /// 姓名
    /// </summary>
    public string FullName { get; set; } = string.Empty;
    
    /// <summary>
    /// 手机号
    /// </summary>
    public string? PhoneNumber { get; set; }
}

/// <summary>
/// 创建用户命令处理器
/// </summary>
public class CreateUserCommandHandler : IRequestHandler<CreateUserCommand, Result<User>>
{
    private readonly IUserRepository _userRepository;
    
    public CreateUserCommandHandler(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }
    
    public async Task<Result<User>> Handle(CreateUserCommand request, CancellationToken cancellationToken)
    {
        // 验证用户名是否已存在
        if (await _userRepository.ExistsByUsernameAsync(request.Username))
        {
            return Result<User>.Failure("用户名已存在");
        }
        
        // 验证邮箱是否已存在
        if (await _userRepository.ExistsByEmailAsync(request.Email))
        {
            return Result<User>.Failure("邮箱已存在");
        }
        
        // 创建密码哈希（这里应该使用更安全的哈希算法）
        var passwordHash = BCrypt.Net.BCrypt.HashPassword(request.Password);
        
        // 创建用户
        var user = User.Create(
            request.Username,
            request.Email,
            passwordHash,
            request.FullName,
            request.PhoneNumber);
        
        // 保存用户
        await _userRepository.AddAsync(user);
        
        return Result<User>.Success(user);
    }
} 